<template>
  <div id="storeOrdersPage">
    <div class="page-header">
      <h1 class="page-title">门店订单</h1>
    </div>

    <!-- 订单列表 -->
    <a-card :bordered="false">
      <a-table
        :data-source="orderList"
        :loading="loading"
        :pagination="{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条`,
          onChange: handleTableChange,
          onShowSizeChange: handleTableChange
        }"
        :row-key="record => record.orderId"
      >
        <template #title>
          <div class="table-header">
            <span>订单列表</span>
            <a-space>
              <a-select
                v-model:value="orderStatus"
                style="width: 120px"
                placeholder="订单状态"
                @change="handleStatusChange"
              >
                <a-select-option value="all">全部</a-select-option>
                <a-select-option value="0">待支付</a-select-option>
                <a-select-option value="1">已支付</a-select-option>
                <a-select-option value="2">制作中</a-select-option>
                <a-select-option value="3">已完成</a-select-option>
                <a-select-option value="4">已取消</a-select-option>
              </a-select>
              <a-range-picker
                v-model:value="dateRange"
                @change="handleDateChange"
              />
            </a-space>
          </div>
        </template>

        <a-table-column title="订单信息" data-index="orderId">
          <template #default="{ record }">
            <div class="order-info">
              <div class="order-header">
                <span class="order-id">订单编号：{{ record.orderId }}</span>
                <a-tag :color="getStatusColor(record.status)">
                  {{ getStatusText(record.status) }}
                </a-tag>
              </div>
              <div class="order-details">
                <div class="detail-item">
                  <span class="label">下单时间：</span>
                  <span>{{ record.createTime }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">取餐码：</span>
                  <span>{{ record.pickCode }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">顾客姓名：</span>
                  <span>{{ record.username }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">联系电话：</span>
                  <span>{{ record.phone }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">订单金额：</span>
                  <span class="price">¥{{ record.totalPrice }}</span>
                </div>
                <div class="detail-item" v-if="record.remark">
                  <span class="label">备注：</span>
                  <span>{{ record.remark }}</span>
                </div>
              </div>
            </div>
          </template>
        </a-table-column>

        <a-table-column title="商品信息" data-index="orderItemList">
          <template #default="{ record }">
            <div class="order-items">
              <div v-for="item in record.orderItemList" :key="item.productId" class="order-item">
                <div class="item-header">
                  <div class="item-info">
                    <img v-if="item.imageUrlList && item.imageUrlList.length > 0"
                         :src="item.imageUrlList[0]"
                         class="item-image"
                         alt="商品图片">
                    <span class="item-name">{{ item.name }}</span>
                  </div>
                  <span class="item-price">¥{{ item.price }}</span>
                </div>
                <div class="item-details">
                  <span class="item-quantity">数量: {{ item.quantity }}</span>
                  <div class="item-params" v-if="item.paramList && item.paramList.length > 0">
                    <a-tag
                      v-for="param in item.paramList"
                      :key="param.paramValueId"
                      class="param-tag"
                    >
                      {{ param.paramValueName }}
                    </a-tag>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </a-table-column>

        <a-table-column title="操作" width="120" fixed="right">
          <template #default="{ record }">
            <a-button
              v-if="record.status === 1"
              type="primary"
              size="small"
              @click="handleAcceptOrder(record)"
            >
              接单
            </a-button>
            <a-button
              v-if="record.status === 2"
              type="primary"
              size="small"
              @click="handleCompleteOrder(record)"
            >
              出餐
            </a-button>
          </template>
        </a-table-column>
      </a-table>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';
import { useStoreMsgStore } from "@/store/useStoreMsgStore";
import { message } from 'ant-design-vue';
import { listOrder, receiveOrder, finishMaking } from '@/api/order';
import { listPermission } from '@/api/permission';
import type { Dayjs } from 'dayjs';

// 获取门店ID
const storeMsg = useStoreMsgStore();

// WebSocket连接
let ws: WebSocket | null = null;
let reconnectTimer: number | null = null;
const isConnected = ref(false);

// 订单列表
const orderList = ref<any[]>([]);
const loading = ref(false);
const orderStatus = ref('all');
const dateRange = ref<[Dayjs, Dayjs] | null>(null);

// 分页参数
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
});

// 获取状态颜色
const getStatusColor = (status: number) => {
  const colorMap: Record<number, string> = {
    0: 'processing',
    1: 'success',
    2: 'warning',
    3: 'success',
    4: 'error'
  };
  return colorMap[status] || 'default';
};

// 获取状态文本
const getStatusText = (status: number) => {
  const textMap: Record<number, string> = {
    0: '待支付',
    1: '已支付',
    2: '制作中',
    3: '待取餐',
    4: '已取消',
    10: '已完成'
  };
  return textMap[status] || '未知状态';
};

// 处理表格变化（分页、排序、筛选）
const handleTableChange = (page: number, pageSize: number) => {
  pagination.value.current = page;
  pagination.value.pageSize = pageSize;
  fetchOrderList();
};

// 处理状态筛选
const handleStatusChange = (value: string) => {
  orderStatus.value = value;
  pagination.value.current = 1; // 重置页码
  fetchOrderList();
};

// 处理日期筛选
const handleDateChange = (dates: [Dayjs, Dayjs] | null) => {
  dateRange.value = dates;
  pagination.value.current = 1; // 重置页码
  fetchOrderList();
};

// 获取订单列表
const fetchOrderList = async () => {
  if (!storeMsg.storeId) {
    message.error('未获取到门店信息');
    return;
  }

  loading.value = true;
  try {
    // 获取日期范围
    let startTime = '';
    let endTime = '';
    if (dateRange.value) {
      startTime = dateRange.value[0].format('YYYY-MM-DD HH:mm:ss');
      endTime = dateRange.value[1].format('YYYY-MM-DD HH:mm:ss');
    } else {
      const today = new Date();
      startTime = today.toISOString().split('T')[0] + ' 00:00:00';
      endTime = today.toISOString().split('T')[0] + ' 23:59:59';
    }

    const param = {
      storeId: storeMsg.storeId,
      status: orderStatus.value === 'all' ? -1 : parseInt(orderStatus.value),
      startTime,
      endTime,
      pageNum: pagination.value.current,
      pageSize: pagination.value.pageSize
    };

    const res = await listOrder(param);
    if (res.data.code === 200) {
      orderList.value = res.data.data.list;
      pagination.value.total = res.data.data.total;
      pagination.value.pageSize = res.data.data.pageSize;
      pagination.value.current = res.data.data.pageNum;
    } else {
      message.error(res.data.msg || '获取订单列表失败');
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
    message.error('获取订单列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

const initWebSocket = () => {
  // 检查 storeId 是否存在
  if (!storeMsg.storeId) {
    message.error('未获取到门店信息，无法建立连接');
    return;
  }

  // 如果已经存在连接，先关闭
  if (ws) {
    ws.close();
  }

  try {
    // 创建WebSocket连接，传递storeId
    const wsUrl = `ws://localhost:8888/ws/${storeMsg.storeId}`;
    console.log('正在连接 WebSocket:', wsUrl);
    ws = new WebSocket(wsUrl);

    // 连接建立时的处理
    ws.onopen = () => {
      console.log('WebSocket连接成功');
      isConnected.value = true;
      // 清除重连定时器
      if (reconnectTimer) {
        clearTimeout(reconnectTimer);
        reconnectTimer = null;
      }
    };

    // 接收消息
    ws.onmessage = (event) => {
      const order = JSON.parse(event.data);
      console.log('收到新订单:', order);
      // 重新获取订单列表
      fetchOrderList();
      message.success('收到新订单！');
    };

    // 连接关闭
    ws.onclose = (event) => {
      console.log('WebSocket连接关闭', event.code, event.reason);
      isConnected.value = false;
      // 尝试重连
      if (!reconnectTimer) {
        reconnectTimer = window.setTimeout(() => {
          console.log('尝试重新连接...');
          initWebSocket();
        }, 3000); // 3秒后重试
      }
    };

    // 连接错误
    ws.onerror = (error) => {
      console.error('WebSocket错误:', error);
      console.error('WebSocket 状态:', ws?.readyState);
      isConnected.value = false;
    };
  } catch (error) {
    console.error('创建WebSocket连接失败:', error);
    message.error('创建WebSocket连接失败');
  }
};

// 处理接单
const handleAcceptOrder = async (record: any) => {
  try {
    const res = await receiveOrder(record.orderId);
    if (res.data.code === 200) {
      message.success('接单成功');
      // 刷新订单列表
      fetchOrderList();
    } else {
      message.error(res.data.msg || '接单失败');
    }
  } catch (error) {
    console.error('接单失败:', error);
    message.error('接单失败，请稍后重试');
  }
};

// 处理出餐
const handleCompleteOrder = async (record: any) => {
  try {
    const res = await finishMaking(record.orderId);
    if (res.data.code === 200) {
      message.success('出餐成功');
      // 刷新订单列表
      fetchOrderList();
    } else {
      message.error(res.data.msg || '出餐失败');
    }
  } catch (error) {
    console.error('出餐失败:', error);
    message.error('出餐失败，请稍后重试');
  }
};

// 添加检查门店信息的函数
const checkStoreInfo = async () => {
  try {
    const res = await listPermission();
    if (res.data.code === 200) {
      const havaStore = res.data.data.havaStore;
      if (havaStore === false) {
        // 如果没有门店信息，1秒后重试
        setTimeout(checkStoreInfo, 1000);
        return;
      }
      // 有门店信息，继续初始化
      fetchOrderList();
      initWebSocket();
    }
  } catch (error) {
    console.error('检查门店信息失败:', error);
    // 发生错误时，1秒后重试
    setTimeout(checkStoreInfo, 1000);
  }
};

// 在组件挂载时初始化连接
onMounted(() => {
  checkStoreInfo();
});

// 在组件卸载时关闭连接
onUnmounted(() => {
  if (ws) {
    ws.close();
  }
  if (reconnectTimer) {
    clearTimeout(reconnectTimer);
  }
});
</script>

<style scoped>
#storeOrdersPage {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
  padding: 16px 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #1f1f1f;
  margin: 0;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
}

.order-info {
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
  margin: 8px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px dashed #e8e8e8;
}

.order-id {
  font-size: 15px;
  font-weight: 500;
  color: #1f1f1f;
}

.order-details {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.detail-item {
  color: #595959;
  font-size: 14px;
  line-height: 1.5;
}

.detail-item .label {
  color: #8c8c8c;
  margin-right: 8px;
}

.detail-item .price {
  color: #ff4d4f;
  font-weight: 500;
}

.order-items {
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
  margin: 8px;
}

.order-item {
  padding: 16px;
  background: #fff;
  border-radius: 6px;
  margin-bottom: 12px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.order-item:last-child {
  margin-bottom: 0;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px dashed #f0f0f0;
}

.item-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.item-image {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  object-fit: cover;
}

.item-name {
  font-size: 15px;
  font-weight: 500;
  color: #1f1f1f;
}

.item-price {
  color: #ff4d4f;
  font-weight: 500;
  font-size: 15px;
}

.item-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 8px;
}

.item-quantity {
  color: #595959;
  font-size: 14px;
}

.item-params {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 4px;
}

.param-tag {
  margin: 0;
  background: #f5f5f5;
  border: 1px solid #e8e8e8;
  color: #595959;
  font-size: 12px;
  padding: 0 8px;
  height: 22px;
  line-height: 20px;
}

:deep(.ant-table-cell) {
  padding: 0 !important;
}

:deep(.ant-card-body) {
  padding: 0;
}

:deep(.ant-table) {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 500;
}

:deep(.ant-select-selector) {
  border-radius: 6px !important;
}

:deep(.ant-picker) {
  border-radius: 6px !important;
}

:deep(.ant-tag) {
  border-radius: 4px;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
  font-size: 13px;
}
</style>
